package smlab.utils
{
	import mx.controls.*;
	import mx.utils.StringUtil;
	import mx.validators.*;
	
	/**
	 * 身份证验证
	 * @author simon
	 * 
	 */
	public class IDUtils extends Validator
	{
		public function IDUtils()
		{
			//TODO: implement function
			super();
		}
		
		private var _certNoError:String;
		
		public function set certNoError(certNoError:String):void
		{
			this._certNoError = certNoError;
		}
		
		public function get certNoError():String
		{
			return this._certNoError;
		}
		
		public static function validateCertNo(validator:IDUtils,value:Object,baseField:String = null):Array
		{
			var results:Array = [];
			
			var val:String = value != null ? String(value) : "";
			
			if(val.length != 15 && val.length != 18){
				results.push(new ValidationResult(
					true, baseField, "novalid",
					StringUtil.substitute(validator.certNoError, "")));
				return results;
			}
			
			var certNo:String;
			
			if(val.length == 15)
				certNo = val.substring(0,6) + "19" + val.substring(6);                                
			else
				certNo = val.substring(0,17);
			// TODO validate certno of 15 length
			if(val.length == 15)
				return results;
			//
			trace(certNo);
			var ai:Array = [];
			for(var i:int=0;i<17;i++){
				ai.push(certNo.substr(i,1));
			}
			var wi:Array = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
			var sum:int = 0;
			for(var k:int=0;k<17;k++){                
				sum += (int(ai[k])*int(wi[k]));
			}
			var code:int = (sum % 11);
			trace(ai);
			trace(wi);
			trace(sum);
			trace(code);
			var validcode:Array = ['1','0','x','9','8','7','6','5','4','3','2'];
			trace(val.substring(17).toLocaleLowerCase());
			trace(validcode[code]);
			
			if(val.substring(17).toLocaleLowerCase() != validcode[code] ){        
				results.push(new ValidationResult(
					true, baseField, "novalid",
					StringUtil.substitute(validator.certNoError, "")));
				return results;
			}
			
			return results;
		}
		
		override protected function doValidation(value:Object):Array
		{
			var results:Array = super.doValidation(value);
			
			// Return if there are errors
			// or if the required property is set to false and length is 0.
			var val:String = value ? String(value) : "";
			if (results.length > 0){                                
				return results;
			}else{
				return IDUtils.validateCertNo(this, value, null);
			}
		}
	}
}